#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import signal
import sys

from lxml import etree  # lxml是python的一个解析库，支持HTML和XML的解析
# 界面
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QFileDialog, QMainWindow
from PyQt5.QtWidgets import QPushButton, QMessageBox, QLabel
# commomroad-io: https://commonroad.in.tum.de/static/docs/commonroad-io/index.html
from commonroad.common.file_writer import CommonRoadFileWriter
# opendrive标准中的road,lane,lane_section,junction之类的元素
sys.path.append("./opendrive_elements") 

from parser import parse_opendrive
from network import Network
from viewer import MainWindow as ViewerWidget

def main():
    # Make it possible to exit application with ctrl+c on console
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    # Startup application
    app = QApplication(sys.argv)
    _ = MainWindow(sys.argv)
    sys.exit(app.exec_())


class MainWindow(QWidget):
    def __init__(self, argv):
        super().__init__()
        self.loadedRoadNetwork = None
        self._initUserInterface()
        self.show()
        if len(argv) >= 2:
            self.load_opendriveFile(argv[1])
            self.viewLaneletNetwork()
    # 界面大小，显示之类的设置
    def _initUserInterface(self):
        self.setWindowTitle("OpenDrive Viewer")
        self.setFixedSize(700, 360)
        self.loadButton = QPushButton("Load OpenDrive File", self)
        self.loadButton.setToolTip("Load OpenDrive file (*.xodr)")
        self.loadButton.move(10, 10)
        self.loadButton.resize(200, 35)
        self.loadButton.clicked.connect(self.openOpenDriveFileDialog)
        self.inputOpenDriveFile = QLineEdit(self)
        self.inputOpenDriveFile.move(220, 10)
        self.inputOpenDriveFile.resize(450, 35)
        self.inputOpenDriveFile.setReadOnly(True)
        self.statsText = QLabel(self)
        self.statsText.move(10, 55)
        self.statsText.resize(540, 235)
        self.statsText.setAlignment(Qt.AlignLeft | Qt.AlignTop)
        self.statsText.setTextFormat(Qt.RichText)
        self.viewOutputButton = QPushButton("View Road Network", self)
        self.viewOutputButton.move(10, 300)
        self.viewOutputButton.resize(200, 35)
        self.viewOutputButton.setDisabled(True)
        self.viewOutputButton.clicked.connect(self.viewLaneletNetwork)

    def resetOutputElements(self):
        self.viewOutputButton.setDisabled(True)

    def openOpenDriveFileDialog(self):
        self.resetOutputElements()
        path, _ = QFileDialog.getOpenFileName(
            self,
            "QFileDialog.getOpenFileName()",
            "",
            "OpenDRIVE files *.xodr (*.xodr)",
            options=QFileDialog.Options(),
        )
        if not path:
            return
        self.load_opendriveFile(path)

    def load_opendriveFile(self, path):
        filename = os.path.basename(path)
        self.inputOpenDriveFile.setText(filename)        
        try:
            fh = open(path, "r")
            # Load road network and print some statistics
            # 解析地图
            openDriveXml = parse_opendrive(etree.parse(fh).getroot())
            fh.close()
        except (etree.XMLSyntaxError) as e:
            errorMsg = "XML Syntax Error: {}".format(e)
            QMessageBox.warning(
                self,
                "OpenDRIVE error",
                "There was an error during the loading of the selected OpenDRIVE file.\n\n{}".format(
                    errorMsg
                ),
                QMessageBox.Ok,
            )
            return
        except (TypeError, AttributeError, ValueError) as e:
            errorMsg = "Value Error: {}".format(e)
            QMessageBox.warning(
                self,
                "OpenDRIVE error",
                "There was an error during the loading of the selected OpenDRIVE file.\n\n{}".format(
                    errorMsg
                ),
                QMessageBox.Ok,
            )
            return

        self.loadedRoadNetwork = Network()
        self.loadedRoadNetwork.load_opendrive(openDriveXml)

        self.statsText.setText(
            """Name: {}<br>Version: {}<br>Date: {}<br><br>OpenDrive
            Version {}.{}<br><br>Number of roads: {}<br>Total length
            of road network: {:.2f} meters""".format(
                openDriveXml.header.name
                if openDriveXml.header.name
                else "<i>unset</i>",
                openDriveXml.header.version,
                openDriveXml.header.date,
                openDriveXml.header.revMajor,
                openDriveXml.header.revMinor,
                len(openDriveXml.roads),
                sum([road.length for road in openDriveXml.roads]),
            )
        )
        self.viewOutputButton.setDisabled(False)

    # View_Road_Network button
    def viewLaneletNetwork(self):
        class ViewerWindow(QMainWindow):
            def __init__(self, parent=None):
                super(ViewerWindow, self).__init__(parent)
                self.viewer = ViewerWidget(self)
                self.setCentralWidget(self.viewer)
        viewer = ViewerWindow(self)
        # 显示地图
        viewer.viewer.openScenario(self.loadedRoadNetwork.export_commonroad_scenario())
        viewer.show()


if __name__ == "__main__":
    main()
